const path = require("path");
const fs = require("fs");

const USER_HOME = process.env.HOME || process.env.USERPROFILE;
const KEYS = path.join(USER_HOME, ".tinypng_key");

function getKeys() {
  const exists = fs.existsSync(KEYS);

  if (!exists) {
    return [];
  }

  const keys = fs.readFileSync(KEYS, "utf-8");
  return keys
    .split(/\r?\n/)
    .map((v) => v.trim())
    .filter((v) => v);
}

function setKeys(keys) {
  fs.writeFileSync(KEYS, keys.join("\n"));
}

function splitKeys(keys) {
  const _keys = keys?.split(",") ?? [];
  return _keys.map((v) => v.trim()).filter((v) => v);
}

function addKeys(keys) {
  const rawKeys = getKeys();
  const newKeys = splitKeys(keys);

  newKeys.forEach((k) => {
    if (!rawKeys.includes(k)) {
      rawKeys.push(k);
    }
  });

  setKeys(rawKeys);
}

function removeKeys(keys) {
  let rawKeys = getKeys();
  const newKeys = splitKeys(keys);

  rawKeys = rawKeys.filter((k) => !newKeys.includes(k));

  setKeys(rawKeys);
}

function clearKeys() {
  setKeys([]);
}

let keyIndex = 0;

function selectKey() {
  const keys = getKeys();
  return keys[keyIndex++];
}

module.exports = {
  getKeys,
  addKeys,
  removeKeys,
  clearKeys,
  selectKey,
};
